package org.richin.file.util;

import java.io.File;
import java.util.Iterator;
import java.util.NoSuchElementException;

public class FileIterator implements Iterator<File> {
	private static class State {
		final State parent;
		final File[] files;
		int index = 0;

		public State(State parent, File dir) {
			this.parent = parent;
			files = dir.listFiles();
		}
	}

	private File current;

	private State state;

	public FileIterator(File file) {
		if (file.isDirectory()) {
			state = new State(null, file);
			nextInternal();
		} else {
			this.current = file;
			state = null;
		}
	}

	public boolean hasNext() {
		return current != null;

	}

	public File next() {
		File rtValue = current;
		if (rtValue == null)
			throw new NoSuchElementException();
		nextInternal();
		return rtValue;
	}

	private void nextInternal() {
		current = null;
		if (this.state == null)
			return;

		for (;;) {
			if (state.index >= state.files.length) {
				state = state.parent;
				if (state == null)
					return;

				state.index++;
				continue;
			}

			File file = state.files[state.index];

			// 可以在此处加入Filters处理代码
			
			System.out.println(file.getPath());	
		
			if (file.isDirectory()) {
				state = new State(state, file);
				continue;
			}
				current = file;
				state.index++;
				break;	
		}
	}

	public void remove() {
		throw new UnsupportedOperationException();

	}

	public static void main(String[] args) throws InterruptedException {
		File dir = new File("C:\\Documents and Settings\\Administrator\\桌面\\stock\\fileutil_src");
		FileIterator it = new FileIterator(dir);
		while (it.hasNext()) {
						File file = (File) it.next();
			//System.out.println(file.getPath());
		}
	}
}
